<template>
  <div class="loginbox">
    <div class="frombox">
      <div class="fromimg">
        <img src="../assets/logo.png" alt="" />
      </div>
      <el-form
        ref="formreset"
        :rules="loginrules.rules"
        class="formdata"
        :model="formdata"
      >
        <el-form-item prop="username">
          <el-input
            prefix-icon="el-icon-user-solid"
            v-model="formdata.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            prefix-icon="el-icon-lock"
            v-model="formdata.password"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="btns">
        <el-button type="primary" @click="login">登录</el-button>
        <el-button type="info" @click="resetForm">重置</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formdata: {
        username: "",
        password: "",
      },
      loginrules: {
        rules: {
          username: [
            { required: true, message: "请输入名称", trigger: "blur" },
            {
              min: 3,
              max: 8,
              message: "长度在 3 到 8 个字符",
              trigger: "blur",
            },
          ],
          password: [
            { required: true, message: "输入密码", trigger: "change" },
            {
              min: 3,
              max: 12,
              message: "长度在 3 到 12 个字符",
              trigger: "blur",
            },
          ],
        },
      },
    };
  },
  methods: {
    resetForm() {
      this.$refs.formreset.resetFields();
    },
    login() {
      this.$refs.formreset.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post("login", this.formdata);
          if (res.meta.status !== 200) {
            return this.$message.error("登陆失败");
          }
          this.$message.success("登录成功");
          window.sessionStorage.setItem("token", res.data.token);
          this.$router.push("/home");
        } else {
          alert("提交失败，检查名称或者密码");
          return false;
        }
      });
    },
  },
};
</script>

<style  scoped>
.loginbox {
  height: 100%;
  background-color: rgb(36, 49, 55);
}
.frombox {
  width: 400px;
  height: 300px;
  background-color: aliceblue;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.fromimg {
  position: absolute;
  width: 130px;
  height: 130px;
  border-radius: 50%;
  padding: 10px;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
}
.fromimg img {
  width: 100%;
  border-radius: 50%;
  background-color: rgb(236, 238, 235);
}
.formdata {
  margin-top: 90px;
  padding: 20px 20px 0 20px;
}
.btns {
  box-sizing: border-box;
  padding-right: 20px;
  float: right;
}
</style>